﻿angular.module('Caltech').directive('busyClick', function ($parse, $q, toaster, $timeout) {
    'use strict';
    return {
        restrict: 'A',
        priority: 0,
        //terminal: true,
        link: function (scope, element, attrs) {
            var successMessage = attrs.success,
                errorMesssage = attrs.error || 'An error occured, please try again',
                modal = attrs['targetModal'],
                action = $parse(attrs['busyClick']);

            function releaseClick() {
                element.removeAttr('disabled');

                if (modal) {
                    $('#' + modal).modal('hide');
                    //bug
                    $('body').removeClass('modal-open');
                    $('.modal-backdrop').remove();
                }
            }

            element.on('click', function () {
                element.attr('disabled', 'disabled');

                $timeout(function () {
                    var promise = action(scope);

                    if (promise && promise.finally) {
                        promise
                            .then(function (promise) {
                                var def;

                                if (promise && (promise.exceptionMessage || promise.message)) {
                                    def = $q.defer();
                                    def.reject(promise.exceptionMessage || promise.message);
                                    return def.promise;
                                } else if (successMessage) {
                                    toaster.pop('success', "Success", successMessage);
                                }
                            })
                            .catch(function (exception) {
                                if (errorMesssage) {
                                    if (exception.data.exceptionMessage) {
                                        toaster.pop('error', "Error", exception.data.exceptionMessage);
                                    } else {
                                        toaster.pop('error', "Error", errorMesssage);
                                    }

                                }
                            })
                            .finally(function () {
                                releaseClick();
                            });
                    } else {
                        releaseClick();
                    }
                });
            });
        }
    };
});